import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/baoxiu/enusuranceinspector.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/jiance/faultcode.dart';
import 'package:magic_car/jiance/mileagepage.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:date_format/date_format.dart';

//子页面
class EnsuranceStartPage extends StatefulWidget {
  //final String queryid;

  // QuerycarinfoPage(this.queryid);

  @override
  _ChildItemViewState createState() => _ChildItemViewState();
}

class _ChildItemViewState extends State<EnsuranceStartPage> {
  List codelist = [];
  String xsz_url = "";
  TextEditingController chejia = new TextEditingController();
  TextEditingController bussiness = new TextEditingController();
  TextEditingController biaoxianlc = new TextEditingController();
  TextEditingController paizhao = new TextEditingController();
  List bussinesslist = [];
  String bussinessid = "";
  String fadongji = "";
  String applydate = "选择上牌时间";//上牌时间
   List<DateTimePickerLocale> _locales = DateTimePickerLocale.values;

  String _format = 'yyyy-MMMM-dd';
  TextEditingController _formatCtrl = TextEditingController();
  
  String MIN_DATETIME = '2010-05-01';
  String MAX_DATETIME = '2030-11-01';
  String INIT_DATETIME = '2020-05-01';

  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;

  DateTime _dateTime;
  

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
    // getqueryinfo();
  }

  //查询车辆数据
  queryprolems(type, url, vin, recheck) async {
    if (url == "") {
      Toast.show("请上传行驶证", context);
      return;
    }
    if (vin == "") {
      Toast.show("请填写正确的车架号", context);
      return;
    }
    EasyLoading.show(status: "正在生成查询订单");
    Map<String, String> param = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["uid"] = pref.getString('uid');
    param["oid"] = '0';
    param['img'] = url;
    param['vin'] = vin;
    param['type'] = type.toString();
    if (recheck == 1) {
      param['recheck'] = "1";
    }
    HttpHelper.post(HttpHelper.API_Getwxpaycode, (data) async {
      EasyLoading.dismiss();
      if (data != null) {
        Toast.show(data['msg'], context);
        print(data);
        if (data["code"].toString() == "1") {
          //有结果的情况，需要处理结果
          if (data["info"].containsKey('url')) {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return new AlertDialog(
                  title: new Text(
                    '请用微信扫码付款后查询，如无查询结果费用将原路返回',
                    style: TextStyle(fontSize: 14),
                  ),
                  content: new SingleChildScrollView(
                      child: new Image.network(
                    data['info']['url'],
                    width: 300,
                    height: 300,
                    fit: BoxFit.fitHeight,
                  )),
                );
              },
            );
          } else if (data["info"].containsKey('is_check')) {
            //有查询历史的情况
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return new CupertinoAlertDialog(
                    actions: [
                      CupertinoDialogAction(
                          child: Text('查看'),
                          onPressed: () {
                            Navigator.pop(context);
                            if (type == 2) {
                              //历史里程
                              Navigator.of(context)
                                  .push(new MaterialPageRoute(builder: (_) {
                                return new MileAgePage(data['info']['id']);
                              }));
                            } else if (type == 1) {
                              //历史故障码
                              Navigator.of(context)
                                  .push(new MaterialPageRoute(builder: (_) {
                                return new FaultCodePage(data['info']['id']);
                              }));
                            }
                          }),
                      CupertinoDialogAction(
                        child: Text('重新查询'),
                        onPressed: () {
                          Navigator.pop(context);
                          queryprolems(type, xsz_url, chejia.text, 1);
                        },
                      )
                    ],
                    content: new SingleChildScrollView(
                      child: ListBody(
                        children: [
                          Text('车辆已经查询过相关信息，是否查看历史数据'),
                        ],
                      ),
                    ),
                  );
                });
          } else {
            if (type == 2) {
              //历史里程
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new MileAgePage(data['info']['queryid']);
              }));
            } else if (type == 1) {
              //历史故障码
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new FaultCodePage(data['info']['queryid']);
              }));
            }
            // Toast.show('有结果了', context);
          }
        } else {}
      }
    }, params: param);
  }

  //选择时间
  //选择日期组件
  void _showDatePicker() {
    print('选择日期');
    DatePicker.showDatePicker(
      context,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          _dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
         applydate  = formatDate(dateTime, [yyyy, "-", mm, "-", dd]);
        
        });
       
        // setState(() {
        //   _dateTime = dateTime;
        // });
       
      },
    );
  }

  getqueryinfo() async {
    EasyLoading.show(status: "正在查询");
    Map<String, String> param = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["uid"] = pref.getString('uid');
    // param['id'] = widget.queryid;

    HttpHelper.post(HttpHelper.API_QueryHistoryinfo, (data) async {
      EasyLoading.dismiss();
      if (data != null) {
        for (var item in data['info']['problem']) {
          for (var codes in item["codeList"]) {
            codes['time'] = item['updateTime'];
          }
          codelist.addAll(item["codeList"]);
        }
        setState(() {
          codelist = codelist;
        });
      }
    }, params: param);
  }

  //识别行驶证
  scanxsz(url) {
    Toast.show('信息识别中...', context);
    Map<String, String> param = new Map();

    param['img'] = url;
    HttpHelper.post(HttpHelper.API_Scanxsz, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        setState(() {
          xsz_url = url;
        });
        print(data);
        Map response1 = data['Response'];
         if (response1.containsKey("FrontInfo") && response1['FrontInfo'].containsKey('Vin')) {
          chejia.text = response1['FrontInfo']['Vin'];
          if(response1['FrontInfo'].containsKey('RegisterDate'))//RegisterDate
          {
           setState(() {
             applydate = response1['FrontInfo']['RegisterDate'];
           });
          }
           if(response1['FrontInfo'].containsKey('PlateNo'))//RegisterDate
          {
             paizhao.text = response1['FrontInfo']['PlateNo'];
          }
          //EngineNo
           if(response1['FrontInfo'].containsKey('EngineNo'))//RegisterDate
          {
            fadongji = response1['FrontInfo']['EngineNo'];
          }
        }
        
         else {
          Toast.show("没有识别到相关信息", context);
        }
      }
    }, params: param);
  }

  getxszimgs(type, index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();
    Map imgitem;

    HttpHelper.upLoadImageNocompress(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        scanxsz(data["url"]);
        //  setState(() {
        //   xsz_url = data["url"];
        // });
      }
    }, params: map);
  }

  //提交订单

  submitorder() async {
    Map<String, String> param = new Map();
    if (xsz_url == "") {
      Toast.show("请上传行驶证或者vin", context);
      return;
    }
    if (chejia.text == "") {
      Toast.show("请填写正确的车架号", context);
      return;
    }
    if(bussiness.text==""){
       Toast.show("请填写车商名称，如果没有，填无", context);
      return;
    }
    param['vin'] = chejia.text;
    param['img'] = xsz_url;
    param['bussiness'] = bussinessid;
    param['bussinessname'] = bussiness.text;
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["uid"] = pref.getString('uid');
    param['registordate'] = applydate;
    param['platno'] = paizhao.text;
    param['fadongji']= fadongji;
    HttpHelper.post(HttpHelper.API_UpEnsurancecar, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data['code'].toString() == "1") {
          setState(() {
            xsz_url = "";
            bussinessid = "";
           
            
          });
          chejia.text = "";
          bussiness.text="";
          
          //
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new EnsuranceOBDPage(data['info']['id']);
          })).then((param) {});
        }else{
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

  //关键字查找商家
  querybussiness() {
    Map<String, String> param = new Map();

    param['keyword'] = bussiness.text;
    HttpHelper.post(HttpHelper.API_Querybussiness, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data['code'].toString() == "1") {
          //
          setState(() {
            bussinesslist = data['info'];
          });
          popupdatawindow();
        }
      }
    }, params: param);
  }

  popupdatawindow() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return ListView.builder(
              itemCount: bussinesslist.length,
              itemBuilder: (BuildContext context, int index) {
                return InkWell(
                    onTap: () {
                      this.bussiness.text = bussinesslist[index]['name'];
                      setState(() {
                        bussinessid = bussinesslist[index]['id'].toString();
                      });
                      Navigator.pop(context);
                    },
                    child: Container(
                        padding: EdgeInsets.all(15),
                        // clipBehavior: Clip.antiAlias,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            topLeft: const Radius.circular(20.0),
                            topRight: const Radius.circular(20.0),
                          ),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(bussinesslist[index]['name'],style: TextStyle(fontWeight: FontWeight.w600),),
                            Container(
                              height: 5,
                            ),
                            Text(
                              "${bussinesslist[index]['provinceName']}/${bussinesslist[index]['cityName']}/${bussinesslist[index]['address']}",
                              style: TextStyle(
                                  fontSize: 13, color: Colours.dark_bg_gray),
                            )
                          ],
                        )));
              });
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
          title: Text(
            "开始检测",
            style: TextStyle(fontSize: Config.title_size),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: ListView(children: [
          Container(
            padding: new EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("点击上传行驶证（如没有，请上传车辆钢印vin）"),
                Container(
                  height: 10,
                ),
                InkWell(
                    onTap: () {
                      showModalBottomSheet(
                          context: context,
                          builder: (BuildContext context) {
                            return Container(
                              height: 120,
                              child: Column(
                                children: [
                                  Container(
                                    height: 40,
                                    decoration: BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                width: 1,
                                                color: Colours.base_gray))),
                                    child: Center(child: Text('选择图片')),
                                  ),
                                  InkWell(
                                      onTap: () {
                                        Navigator.pop(context);
                                        getxszimgs(0, 1);
                                      },
                                      child: Container(
                                        height: 40,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                bottom: BorderSide(
                                                    width: 1,
                                                    color: Colours.base_gray))),
                                        child: Center(child: Text('相机')),
                                      )),
                                  InkWell(
                                      onTap: () {
                                        Navigator.pop(context);
                                        getxszimgs(1, 1);
                                      },
                                      child: Container(
                                        height: 40,
                                        // decoration: BoxDecoration(
                                        //   border: Border(bottom: BorderSide(
                                        //     width: 1,color: Colours.base_gray
                                        //   ))
                                        // ),
                                        child: Center(child: Text('相册')),
                                      )),
                                ],
                              ),
                            );
                          });
                    },
                    child: Center(
                      child: xsz_url == ""
                          ? Image.asset('resource/images/user/xsz.png',
                              width: 150, height: 150, fit: BoxFit.fitHeight)
                          : CachedNetworkImage(
                              imageUrl: xsz_url,
                              width: MediaQuery.of(context).size.width - 30,
                              // height: 150,
                              fit: BoxFit.fitWidth),
                    )),
                Container(
                  height: 10,
                ),
                Text('填写车架号：'),
                Container(
                  height: 10,
                ),
                Container(
                  decoration: BoxDecoration(color: Colors.white),
                  child: new TextField(
                      maxLength: 17,

                      // inputFormatters: [
                      //   LengthLimitingTextInputFormatter(17), //长度限制17位
                      //   WhitelistingTextInputFormatter(RegExp("[A-Z0-9]")), //只允许输入字母
                      // ],
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp('[0-9A-Z]')),
                        FilteringTextInputFormatter.deny(RegExp('[IOQ]')),
                      ],
                      controller: chejia,
                      decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(
                              vertical: 4.0, horizontal: 10),
                          hintText: "车架号",
                          // suffixText: "车架号",
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ))),
                ),
                Container(
                  height: 10,
                ),
                 Text('上牌日期：'),
                  Container(
                  height: 10,
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(10, 10, 0, 10),
                  height: 40,
                  width: double.infinity-20,
                    decoration:BoxDecoration(color: Colors.white),
                 child: GestureDetector(
                   onTap: (){
                     _showDatePicker();
                   },
                   child: Text(applydate),),
                ),

                //  Text('填写车牌号：'),
                Container(
                  height: 10,
                ),
                 Text('请填写车牌号：'),
                Container(
                  height: 10,
                ),
                Container(
                  decoration: BoxDecoration(color: Colors.white),
                  child: new TextField(
                      controller: paizhao,
                      decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(
                              vertical: 4.0, horizontal: 10),
                          hintText: "车牌号",
                          // suffixText: "车架号",
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ))),
                ),
                Container(
                  height: 10,
                ),
                //  Text('请填写表显里程：'),
                // Container(
                //   height: 10,
                // ),
                // Container(
                //   decoration: BoxDecoration(color: Colors.white),
                //   child: new TextField(
                     

                    
                //       controller: chejia,
                //       decoration: InputDecoration(
                //           contentPadding: const EdgeInsets.symmetric(
                //               vertical: 4.0, horizontal: 10),
                //           hintText: "表显里程",
                //           // suffixText: "车架号",
                //           border: OutlineInputBorder(
                //             borderSide: BorderSide.none,
                //           ))),
                // ),
                // Container(
                //   height: 10,
                // ),
                Text('车辆所属商家：'),
                Container(
                  height: 10,
                ),
                Container(
                    // height: 50,
                    // width: double.infinity-20,
                    decoration: BoxDecoration(color: Colors.white),
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: new TextField(
                                  controller: bussiness,
                                  decoration: InputDecoration(
                                      contentPadding:
                                          const EdgeInsets.symmetric(
                                              vertical: 10.0, horizontal: 10),
                                      hintText: "输入关键字搜索",
                                      // suffixText: "车架号",
                                      border: OutlineInputBorder(
                                        borderSide: BorderSide.none,
                                      )))),
                          new Container(
                            height: 40,

                            // margin: EdgeInsets.all(10),
                            //  height: 40,

                            child: new Card(
                              color: Colours.bj_orange_o1,
                              // color: Color.fromRGBO(242, 185, 20, 1),
                              elevation: 1,
                              child: new FlatButton(
                                child: new Padding(
                                  padding: new EdgeInsets.all(0.0),
                                  child: new Text(
                                    '查找',
                                    style: new TextStyle(
                                        color: Colors.white, fontSize: 16.0),
                                  ),
                                ),
                                onPressed: () {
                                  querybussiness();
                                },
                              ),
                            ),
                          ),
                        ])),
                Container(
                  height: 10,
                ),
                new Container(
                  width: double.infinity,
                  child: new Card(
                    color: Colours.bj_red_r2,
                    // color: Color.fromRGBO(242, 185, 20, 1),
                    elevation: 1,
                    child: new FlatButton(
                      child: new Padding(
                        padding: new EdgeInsets.all(0.0),
                        child: new Text(
                          '下一步',
                          style: new TextStyle(
                              color: Colors.white, fontSize: 16.0),
                        ),
                      ),
                      onPressed: () {
                        submitorder();
                      },
                    ),
                  ),
                ),
                // Container(height: 10,),
                //   new Container(
                //       width: double.infinity,
                //       child: new Card(
                //         color: Colours.bj_green_g1,
                //         // color: Color.fromRGBO(242, 185, 20, 1),
                //         elevation: 1,
                //         child: new FlatButton(
                //           child: new Padding(
                //             padding: new EdgeInsets.all(0.0),
                //             child: new Text(
                //               '查询历史故障',
                //               style: new TextStyle(
                //                   color: Colors.white, fontSize: 16.0),
                //             ),
                //           ),
                //           onPressed: () {

                //            queryprolems(1, xsz_url, chejia.text, 0);
                //           },
                //         ),
                //       ),
                //     )
              ],
            ),
          )
        ]));
  }
}
